﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.IO;
using Shuba.Model;

namespace Shuba.Web.bulk_upload
{
    public partial class branch_rollout_mobile_version_upload : basePage
    {
        string msg = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_BRANCH_ROLLOUT_MOBILE");
                if (!IsUserAdd(acl))
                {
                    msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }
                LabelTitle.Text = GetPageTitle("MSTR_BRANCH_ROLLOUT_MOBILE");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                lblStatus.Text = "";
                status.Visible = false;
            }
            if (IsPostBack)
            {
                Boolean fileOK = false;
                string path = Server.MapPath("~/uploads/");
                string ErrMessage = "";

                if (FileUpload1.HasFile)
                {
                    String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();

                    String[] allowedExtensions = { ".txt", ".csv" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }

                if (fileOK)
                {
                    status.Visible = true;

                    Shuba.Business.BulkUp bulk = new Shuba.Business.BulkUp();

                    string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;

                    bool isSaveToServerSuccess = true;

                    #region Save TO Server
                    try
                    {
                        FileUpload1.PostedFile.SaveAs(fName);
                    }
                    catch
                    {
                        lblStatus.Text = this.GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                        isSaveToServerSuccess = false;
                    }
                    #endregion

                    if (isSaveToServerSuccess)
                    {
                        try
                        {
                            int ErrLine = 0, SuccessCount = 0;
                            var filestream = File.OpenText(fName);
                            string contains = filestream.ReadToEnd();
                            filestream.Close();

                            bool isPending = false;

                            var bsRoll = new Shuba.Business.branch_rollout_mobile_version();
                            var bsBranch = new Shuba.Business.Branch();
                            branch_rollout_versionInfo bInfo = null;

                            char rowDelimiter = '\n';
                            char fldDelimiter = '\t';

                            var rows = contains.Split(rowDelimiter);

                            string errInLine = string.Empty;
                            for (var i = 1; i < rows.Length; i++)
                            {
                                string baris = rows[i].Replace(" ", "");
                                if (baris.Equals("") || baris.Equals("\r")) continue;

                                var fields = rows[i].Split(fldDelimiter);

                                #region Format Data Valid
                                if (fields.Length == 3)
                                {
                                    try
                                    {
                                        string ErrMessageLocal = "";
                                        string branch_id = fields[0].Trim().Replace("'", "`").Replace("\"", "");
                                        string version = fields[1].Trim().Replace("'", "`").Replace("\"", "");
                                        DateTime implementDate = Convert.ToDateTime(fields[2].Trim());

                                        bInfo = bsRoll.Get(branch_id, version);
                                        if (bInfo.BranchID != null && bInfo.version != null)
                                        {
                                            //ErrMessageLocal += "<BR> Branch dengan version ini telah terupload sebelumnya, column : 1, 2 Line :" + i.ToString();
                                        }

                                        if (!isPending && bsRoll.IsPending(branch_id, version))
                                        {
                                            isPending = true;
                                        }

                                        if (bsBranch.Get(branch_id).BranchID == null)
                                        {
                                            ErrMessageLocal += "<BR> Invalid Branch ID, column : 1 Line : " + i.ToString();
                                        }

                                        if (!bsRoll.getVersion().Contains(version))
                                        {
                                            ErrMessageLocal += "<BR> Invalid Version, column : 2 Line : " + i.ToString();
                                        }

                                        if (implementDate.Date < ProcessingDate().Date)
                                        {
                                            ErrMessageLocal += "<BR> Implementation Date tidak boleh kurang dari tanggal sekarang, column : 3 Line : " + i.ToString();
                                        }

                                        if (ErrMessageLocal != "")
                                        {
                                            ErrMessage += ErrMessageLocal;
                                        }

                                        if (ErrMessageLocal == "")
                                        {
                                            bInfo.BranchID = branch_id;
                                            bInfo.version = version;
                                            bInfo.implementation_date = implementDate;
                                            bInfo.is_delete = "0";
                                            bInfo.ActType = "UPLOAD";
                                            bInfo.entry_by = HttpContext.Current.User.Identity.Name;
                                            bInfo.entry_date = ProcessingDate();
                                            bInfo.update_by = HttpContext.Current.User.Identity.Name;
                                            bInfo.update_date = ProcessingDate();

                                            if (bsRoll.Save(bInfo) > 0) SuccessCount++;

                                            AddLog("UPLOAD", "UPLOAD BRANCHROLLOUTMOBILE");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ErrMessage += "<BR> " + GetGlobalResourceObject("Messages", "UploadInvalidFileAlert").ToString() + " Line :" + i.ToString() + " Err : " + ex.Message;
                                        break;
                                    }
                                }
                                #endregion
                                else // Format Data InValid
                                {
                                    ErrMessage += "<BR> " + GetGlobalResourceObject("Messages", "UploadInvalidFileAlert").ToString();
                                    break;
                                }
                            }

                            try 
                            { 
                                File.Delete(fName); 
                            }
                            catch { }

                            if (ErrMessage == "")
                            {
                                lblStatus.Text = msg;
                                FileUpLoadValidator.Visible = false;

                                if (SuccessCount > 0)
                                {
                                    if (isPending)
                                    {
                                        msg = "File Successfully Uploaded\\n\\nSuccessfully Upload : " + SuccessCount + " Record(s)\\n\\nSome data already pending approve";
                                    }
                                    else
                                    {
                                        msg = "File Successfully Uploaded\\n\\nSuccessfully Upload : " + SuccessCount + " Record(s)";
                                    }
                                    AlertAndRedirect(msg, "branch_rollout_mobile_version_list.aspx");
                                }
                                if (SuccessCount == 0 && isPending)
                                {
                                    msg = "Some data already pending approve\\nPlease approve first or change data";
                                    Alert(msg);
                                }
                            }
                            else
                            {
                                status.Visible = true;
                                lblStatus.Text = "<b>Error Found:</b><br>" + ErrMessage + "<br><br><b>Upload Process Stoped at Line: " + ErrLine + "</b>";
                                FileUpLoadValidator.Visible = false;
                            }
                        }
                        catch (Exception ex)
                        {
                            lblStatus.Text = "Error Found: " + ex.Message;
                            FileUpLoadValidator.Visible = false;
                        }
                    }
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("branch_rollout_mobile_version_list.aspx");
        }
    }
}